package com.chinaunicom.order.infrastructure.gateway;

import com.chinaunicom.api.IProductFacadeApi;
import com.chinaunicom.api.dto.ProductSkuDTO;
import com.chinaunicom.api.dto.ProductSkuQuery;
import com.chinaunicom.common.constants.Constants;
import com.chinaunicom.common.exception.BusinessException;
import com.chinaunicom.common.result.JsonResult;
import com.chinaunicom.order.domain.gateway.IProductGateway;
import com.chinaunicom.order.domain.model.entity.OrderItemEntity;
import com.chinaunicom.order.domain.model.entity.ProductSkuEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author guomenghuai
 * @date 2024/1/10
 * @Description
 */
@Slf4j
@Service
public class ProductGateway implements IProductGateway {

    @Reference
    private IProductFacadeApi productFacadeApi;

    @Override
    public List<ProductSkuEntity> convertProductEntity(List<String> skuCodeList, String sellerId) {
        JsonResult<List<ProductSkuDTO>> jsonResult = productFacadeApi.listProductSku(ProductSkuQuery.builder()
                .skuCodeList(skuCodeList)
                .sellerId(sellerId)
                .build());
        log.info("调用商品服务，返回结果：{}", jsonResult);
        if (!StringUtils.equals(Constants.SUCCESS_CODE, jsonResult.getErrorCode()) || Objects.isNull(jsonResult.getData())) {
            throw new BusinessException("调用商品服务失败");
        }

        List<ProductSkuEntity> productSkuEntityList = jsonResult.getData().stream().map(item -> {
            ProductSkuEntity productEntity = new ProductSkuEntity();
            BeanUtils.copyProperties(item, productEntity);
            return productEntity;
        }).collect(Collectors.toList());
        return productSkuEntityList;
    }

}
